from Tkinter import ALL

class LayerManager(object):
    def __init__(self, canvas):
        self.canvas = canvas
        self.layers = []
        self.object = dict()
        
    def add_layer(self, layer):
        if layer in self.object:
            return
        self.layers.append(layer)
        self.layers.sort()
        # create an invisible object which we will use to 
        # correctly draw objects in the canvas by layers
        rect = self.canvas.create_rectangle(0, 0, 10, 10, fill=None, width=0)
        self.object[layer] = rect
        # establish a relation of order between this layer and the others
        above = self.layer_above(layer)
        if above is None:
            self.canvas.tag_raise(rect, ALL)
        else:
            self.canvas.tag_lower(rect, self.object[above])
            
    def del_layer(self, layer):
        object = self.object.pop(layer)
        self.layers.remove(layer)
        self.canvas.delete(object)
        
    def layer_below(self, layer):
        index = self.layers.index(layer)
        if index == 0:
            return None
        return self.layers[index - 1]
        
    def layer_above(self, layer):
        index = self.layers.index(layer)
        if index == len(self.layers) - 1:
            return None
        return self.layers[index + 1]
        
    def layers_around(self, layer):
        index = self.layers.index(layer)
        below = None
        above = None
        if index > 0:
            below = self.layers[index - 1]
        if index < len(self.layers) - 1:
            above = self.layers[index + 1]
        return below, above
        
    def set(self, tag_or_id, layer):
        if layer not in self.object:
            self.add_layer(layer)
        above = self.layer_above(layer)
        if above is None:
            self.canvas.tag_raise(tag_or_id, ALL)
        else:
            self.canvas.tag_lower(tag_or_id, self.object[above])
            